package ar.edu.utn.frsf.tpae.a2012.g04.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import ar.edu.utn.frsf.tpae.a2012.g04.dao.CajaAhorroDao;
import ar.edu.utn.frsf.tpae.a2012.g04.dominio.CajaAhorro;
import ar.edu.utn.frsf.tpae.a2012.g04.dominio.Movimiento;

public class CajaAhorroHibernateDao implements CajaAhorroDao {

	 private SessionFactory sessionFactory = new AnnotationConfiguration()
     .configure().buildSessionFactory();
	 
	@Override
	public CajaAhorro persistir(CajaAhorro cajaAhorro) {
		Session session = sessionFactory.openSession();
	    session.beginTransaction();
	    session.saveOrUpdate(cajaAhorro);
	    session.getTransaction().commit();
	    session.close();
	    return cajaAhorro;
	}

	@Override
	public void eliminar(CajaAhorro cajaAhorro) {
		Session session = sessionFactory.openSession();
	    session.beginTransaction();
	    session.delete(cajaAhorro);
	    session.getTransaction().commit();
	    session.close();

	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<CajaAhorro> listar() {
		 Session session = sessionFactory.openSession();
		    Query query = session.createQuery("from " + CajaAhorro.class.getName());
		    List<CajaAhorro> list = query.list();
		    session.close();
		    return list;
	}

	@Override
	public CajaAhorro buscarPorId(Integer id) {
		Session session = sessionFactory.openSession();
		return (CajaAhorro) session.get(CajaAhorro.class, id);
	}

	@Override
	public CajaAhorro buscarPorNumero(String numero) {
		Session session = sessionFactory.openSession();
	    Query query = session.createQuery("from " + CajaAhorro.class.getName() + " ca where ca.numero = :numero" );
	    query.setString("numero", numero);
	    CajaAhorro cajaAhorro = (CajaAhorro) query.uniqueResult();
		return cajaAhorro;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Movimiento> verMovimientos(CajaAhorro cajaAhorro) {
	    Session session = sessionFactory.openSession();
	    Query query = session.createQuery("from " + Movimiento.class.getName() + " m where m.cuenta.id = :id" );
	    query.setInteger("id", cajaAhorro.getId());
	    List<Movimiento> list = query.list();
	    session.close();
		return list;
	}

}
